package com.jsm.tf.net.command;

import com.jsm.tf.entity.User;
import com.jsm.tf.net.message.request.RoomChatMessage;
import com.jsm.tf.net.message.response.RoomChatResponseMessage;
import com.jsm.tf.net.session.ISessionManager;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Set;

@Component
public class RoomChatMessageCommand implements Command<RoomChatMessage> {
    @Resource
    private ISessionManager sessionManager;

    @Override
    public void execute(RoomChatMessage message, Channel channel) {
        User sendUser = sessionManager.getUserByChannel(channel);
        Long roomId = sessionManager.getRoomId(sendUser);
        Set<User> users = sessionManager.getRoomUsers(roomId);
        if (!CollectionUtils.isEmpty(users)) {
            for (User user : users) {
                Channel userChannel = sessionManager.getChannelByUser(user);
                RoomChatResponseMessage responseMessage = new RoomChatResponseMessage();
                responseMessage.setSendUserNickname(sendUser.getNickname());
                responseMessage.setContent(message.getContent());
                responseMessage.setSeq(message.getSeq());
                userChannel.writeAndFlush(responseMessage);
            }
        }
    }
}
